var Tasks = {

	init:function(){
		if(!window.localStorage){return;}
		var $ul = $('#codes');	
		$ul.empty()
		if(!this.codes){return;}
		var items = JSON.parse(this.codes);
		var html  = [];

		for(var key in items){
			var code = items[key];
			html.push('<li><a>'+key+'</a><i class="del"></i></li>');
		}
		$ul.html(html.join(''));
	},
	add:function(name,code){
		var items = {};
		if(this.codes!=null){
			items = JSON.parse(this.codes);
		}
		items[name] = code;
		this.codes =  localStorage.codes =JSON.stringify(items);
		this.init();
	},
	remove:function(name){
		var items = {};
		if(!this.codes!=null){
			items = JSON.parse(this.codes);
		}
		delete items[name];
		this.codes =  localStorage.codes =JSON.stringify(items);
		this.init();
	},
	codes:localStorage.codes
};

$(function(){
	Tasks.init();
	$('#save').click(function(){

		var title = $('#title').val();
		var code = $('#code').val();
		if(title == '' ){
			$('#title').focus();
			return;
		}
		if(code == '' ){
			$('#code').focus();
			return;
		}
		Tasks.add(title,code);
	});

	$('#codes').delegate('li a','click',function(){
		var items = {};
		if(Tasks.codes != null){
			items = JSON.parse(Tasks.codes);
		}
		var txt = $(this).text();
		var code = items[txt];
		$('#title').val(txt);
		$('#code').val(code);
	}).delegate('li .del','click',function(){
		var txt = $(this).prev().text();
		Tasks.remove(txt);
	});


});